"use strict";
/**
 * @name create
 * 创建角色
 */
const mvc = require("cosjs.mvc");
/**
 * @name /
 * @param string name 用户名（游戏昵称）
 * 创建新角色
 */
module.exports = function register() {
    let name = this.get('name', 'string');
    // console.log("name -----:",name)
    let guid = this.session.get('guid');
    if (!guid) {
        return this.error('guid empty');
    }
    let role = this.model.mongo('role', this.sid);
    let usrData = { "sid": this.sid, "guid": guid, "name": name };
    let coord = [3];
    let buildingsData = {};
    return Promise.resolve().then(() => {
        return this.library('guid/unique', role, name);
    }).then((ret) => {
        if (ret) {
            this.roleNameLocks = ret;
        }
        //验证角色数量
        let role_limit = this.config.get('role.limit');
        if (!role_limit) {
            return 0;
        }
        return role.findFromGuid(guid, 'name').then(ret => {
            if (ret && ret.length >= role_limit) {
                return this.error('register_rnum_limit', ret.length, role_limit);
            }
        })
    }).then(() => {
        return this.library('guid/uid', this.sid);
    }).then(uid => {
        let time = Date.now();
        this.uid = uid;
        usrData['_id'] = uid;
        usrData['time'] = time;
        usrData['login'] = 0;
        //自定义字段
        let register = this.config.get('role.register');
        if (Array.isArray(register)) {
            for (let opt of register) {
                usrData[opt['key']] = this.get(opt['key'], opt['type']);
            }
        }
        mvc.format('role', usrData, true);

        return role.insert(usrData, { 'j': true })
    }).then(ret => {
        //初始道具
        this.updater.role.set("install", 1);
        let install = this.config("install") || {};
        let exileMapItemId = this.config('base', 'exileMapItemId').val;

        for (let k in install) {
            //初始化放逐之地槽位数量
            if (install[k]["id"] == exileMapItemId) {
                this.updater.role.set('deadAreaContainer', install[k]["val"]);
                continue;
            }
            this.updater.add(install[k]["id"], install[k]["val"]);
        }
        //初始化孵蛋器
        let incubateList = {};
        let incubatorConfig = this.config('Incubator');
        for (let item in incubatorConfig) {
            if (incubatorConfig[item].unlockBuildLevel == 0) {
                incubateList[item] = { "eggID": '', "beginTime": '' };
            }
        }
        this.updater.role.set('incubateList', incubateList);
        //'appUnit.' + key
        //config data
        let defaultAssistants = this.config('base', 'defaultAssistant').strVal;
        let assistantArr = defaultAssistants.split(',');
        this.updater.role.set("appUnit", { "backgroud": "", "unit01": assistantArr[0], "unit02": assistantArr[1] });
        // this.updater.role.set('buildingsInfo', buildingsInfo);

        //配置初始建筑 TODO
        // let buildConfig = this.config('baseBuild');
        // let i = 0;
        // for (let build in buildConfig) {
        //     coord[i++] = buildConfig[build].posX + ',' + buildConfig[build].posY + ',' + buildConfig[build].rotate;
        //     this.updater.add(parseInt(build), 1);
        //     // this.updater.role.set('buildingsInfo',{buildingsData});
        // }
        // let mainBuildId = this.config("base", "basicBuildId").val;
        // this.updater.add(mainBuildId, 1);
        return this.updater.save();
    }).then(() => {
        //     //获得初始化建筑的_id，设置到role的 buildingsInfo 中
        //     //获取基础建筑id
        //     // let baseBuildConfig = this.config('baseBuild');
        //     let mainBuildId = this.config("base", "basicBuildId").val;
        //     let buildArr = [];
        //     let i = 0;
        //     for (let item in baseBuildConfig) {
        //         buildArr[i] = item;
        //         i++;
        //     }
        //     let cache = this._handle_updater._update_cache;
        //     for (let item of cache) {
        //         if (item.id == buildArr[0]) {
        //             let buildId = item._id;
        //             buildingsData[buildId] = coord[0];
        //         } else if (item.id == buildArr[1]) {
        //             let buildId = item._id;
        //             buildingsData[buildId] = coord[1];
        //         } else if (item.id == buildArr[2]) {
        //             let buildId = item._id;
        //             buildingsData[buildId] = coord[2];
        //         }
        //     }

        //     this.updater.role.set('buildingsInfo', { buildingsData });
        //     return this.updater.save();
        // }).then(() => {
        if (this.roleNameLocks) {
            this.roleNameLocks.clear();
        }
        this.updater._update_cache = [];
        return Object.from(usrData, ['_id', "name", "lv", "time"]);
    }).catch(err => {
        if (this.roleNameLocks) {
            this.roleNameLocks.clear();
        }
        return Promise.reject(err);
    })
};

/**
 * @name verify
 * @param string name 用户名（游戏昵称）
 * 检查名字是否合法
 */

module.exports.verify = function verify() {
    let name = this.get('name', 'string');
    if (!this.library("/guid/verify", name)) {
        return this.error('register_name_verify', 'name cannot begin with numbers');
    }
    let query = { "name": name }
    let role = this.model.mongo('role', this.sid);
    return role.count(query);
}